<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>工况状态</title>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
      body {
        position: relative;
      }
      .chart {
        width: 100%;
        height: 100%;
      }
      .time-box {
        position: absolute;
        right: 20px;
        top: 5px;
        display: flex;
        align-items: center;
      }
      .time-box > div {
        font-size: 12px;
        line-height: 12px;
        padding: 3px 6px;
        border: 1px solid #47a8ea;
        border-radius: 4px;
      }
      .time-box > div:not(:first-child) {
        margin-left: 5px;
      }
      .today {
        /* background-color: #fff; */
        color: #47a8ea;
      }
      .pre,
      .next {
        background-color: #47a8ea;
        color: #fff;
        cursor: pointer;
      }
      .color{
        color: #909399;
        color: #86eafc;
        color: #087ff7;
        color: #07c160;
        color: #ffa500;
        color: #ee0a24;
        color: #909399;
      }
    </style>
  </head>
  <body>
    <div id="chart" class="chart"></div>
    <div class="time-box">
      <div class="pre" onclick="preDate()">前一天</div>
      <div class="today" id="today"></div>
      <div class="next" onclick="nextDate()">后一天</div>
    </div>
    <script src="./echarts/echarts.min.js"></script>
    <script>
      Date.prototype.Format = function (fmt) {
        let o = {
          "M+": this.getMonth() + 1, //月份
          "d+": this.getDate(), //日
          "h+": this.getHours(), //小时
          "m+": this.getMinutes(), //分
          "s+": this.getSeconds(), //秒
          "q+": Math.floor((this.getMonth() + 3) / 3), //季度
          S: this.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        for (let k in o) {
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length === 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            );
        }
        return fmt;
      };

      var statusText = {
        0: { text: "NULL", color: "#909399" },
        1: { text: "手动", color: "#86eafc" },
        2: { text: "自动", color: "#087ff7" },
        3: { text: "报警", color: "#ee0a24" },
        4: { text: "报警", color: "#ee0a24" },
        5: { text: "自动作业", color: "#07c160" },
        6: { text: "自动空闲", color: "#ffa500" },
      };
      var dateView = new Date().Format("yyyy-MM-dd");
      var chart = echarts.init(document.getElementById("chart"));
      var queryParams = queryUrl();

      window.onload = function () {
        if (queryParams) {
          getData();
        } else {
          document.querySelector(".time-box").remove();
        }
      };

      window.onresize = (e) => {
        chart.resize();
      };

      function preDate() {
        dateView = new Date(new Date(dateView).getTime() - 86400 * 1000).Format(
          "yyyy-MM-dd"
        );
        getData();
      }

      function nextDate() {
        dateView = new Date(new Date(dateView).getTime() + 86400 * 1000).Format(
          "yyyy-MM-dd"
        );
        getData();
      }

      function getData() {
        ajax({
          url: "/iot_report/getDevStatusList",
          data: {
            device_id: queryParams.device_id,
            device_model_id: queryParams.model_id,
            filter_date: dateView,
          },
          type: "get",
          success: function (res) {
            if (typeof res === "string") {
              res = JSON.parse(res);
              var seriesData = [];
              var data = res.data || []
              data.forEach((item) => {
                seriesData.push({
                  name: statusText[item.status].text,
                  type: "bar",
                  barWidth: "100%",
                  stack: "total",
                  emphasis: {
                    focus: "none",
                  },
                  itemStyle: {
                    color: statusText[item.status].color,
                  },
                  data: [item.duration],
                });
              });
              option = {
                legend: {
                  top: 5,
                  left: 20,
                  itemWidth: 12,
                  itemHeight: 12,
                  textStyle: {
                    color: "inherit",
                    fontSize: 12,
                  },
                },
                grid: {
                  left: 0,
                  right: 30,
                  top: 30,
                  bottom: 10,
                  containLabel: true,
                },
                xAxis: {
                  type: "value",
                  alignTicks: true,
                  splitNumber: 24,
                  max: 24,
                  splitLine: {
                    show: false,
                  },
                  axisLine: {
                    show: true,
                    lineStyle:{
                      color:'#00FFFF'
                    }
                  },
                  axisTick: {
                    show: true,
                    lineStyle:{
                      color:'#00FFFF'
                    }
                  },
                  minorTick: {
                    show: true,
                    splitNumber: 6,
                    lineStyle:{
                      color:'#00FFFF'
                    }
                  },
                },
                yAxis: {
                  show: false,
                  type: "category",
                  data: ["工况"],
                },
                series: seriesData,
              };
              chart.setOption(option, true);
              document.getElementById("today").innerText = dateView;
            }
          },
        });
      }

      function ajax(option) {
        //用户配置option 默认配置init
        var init = {
          type: "get",
          async: true,
          url: "",
          success: function () {},
          error: function () {},
          data: {},
          beforeSend: function () {
            // console.log("发送前...");
            return true;
          },
        };
        //TODO step1: 合并参数
        for (k in option) {
          init[k] = option[k];
        }
        //TODO step2: 参数转换
        var params = "";
        for (k in init.data) {
          params += "&" + k + "=" + init.data[k];
        }
        var xhr = new XMLHttpRequest();
        // type url
        //TODO step3: 区分get和post,进行传参
        var url = init.url + "?__=" + new Date().getTime();
        //TODO step4: 发送前
        var flag = init.beforeSend();
        if (!flag) {
          return;
        }
        if (init.type.toLowerCase() == "get") {
          url += params;
          xhr.open(init.type, url, init.async);
          xhr.send();
        } else {
          xhr.open(init.type, url, init.async);
          xhr.setRequestHeader(
            "content-type",
            "application/x-www-form-urlencoded"
          );
          xhr.send(params.substr(1));
        }
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4) {
            if (xhr.status == 200) {
              init.success(xhr.responseText);
            } else {
              //error
              init.error();
            }
          }
        };
      }

      function queryUrl() {
        let result = null;
        var arr = location.search.split("?")?.[1]?.split("&") || [];
        if (arr.length > 0) {
          result = {};
          arr.forEach((item) => {
            result[item.split("=")[0]] = item.split("=")[1];
          });
        }
        return result;
      }
    </script>
  </body>
</html>
